package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.PutCache;
import service.Util;

import model.News;
import model.NewsRecent;
import model.Tags;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class TagsServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		
		resp.setHeader( "Cache-Control", "public, max-age=14400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        String page = "1";

		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		
		if(count != 2 && count != 3)
        {
        	try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return ;
        }
		if(count == 3)
		{
			page = st.nextToken();
		}
		System.out.println(page+"asd");
		if(title_url!=null)
		{
			try {
				ObjectifyService.register(Tags.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Objectify objectify = ObjectifyService.begin();
			try {
				Tags tag = objectify.get(new Key<Tags>(Tags.class, title_url));
				req.setAttribute("tag", tag);
				
				
				try {
					ObjectifyService.register(News.class);
				} catch (Exception e) {
					e.printStackTrace();
				}
				Objectify objectify1 = ObjectifyService.begin();
				
				ArrayList<String> category = PutCache.getCacheList("category");
				
				ArrayList<Query<News>> listCate = new ArrayList<Query<News>>(); 
				if(category.size()>0)
				{
					for (int j = 0; j < category.size(); j++) {
						ArrayList<NewsRecent> cacheCcategory = PutCache.getCacheNews(category.get(j));
						if(cacheCcategory.size()<=0)
						{
							Query<News> list1 = objectify.query(News.class).filter("categoryAlias", category.get(j)).order("-date").limit(5);

							ArrayList<News> arrayList = Util.convertArrayList(list1);
							
							for(int i=(arrayList.size()-1);i>=0;i--)
							{
								NewsRecent newsRecent = new NewsRecent();
								newsRecent.setDate(arrayList.get(i).getDate());
								newsRecent.setThumb(arrayList.get(i).getThumb());
								newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
								newsRecent.setCategory(arrayList.get(i).getCategory());
								newsRecent.setDes(Util.cutDescription(arrayList.get(i).getContent().getValue()));
								
								PutCache.putCacheNews(newsRecent, category.get(j), 5);
							}
							
						}
					}
				}
				
				req.setAttribute("listCate", listCate);
				req.setAttribute("page", page);
				
			} catch (Exception e) {
				
			}
		}
		
		try {
			req.getRequestDispatcher("/tag.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
